package com.utils;

import com.framework.util.SystemUtil;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.NullCacheStorage;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

import java.io.File;
import java.io.IOException;

/*
                           _ooOoo_
                          o8888888o
                          88" . "88
                          (| -_- |)
                          O\  =  /O
                       ____/`---'\____
                     .'  \\|     |//  `.
                    /  \\|||  :  |||//  \
                   /  _||||| -:- |||||-  \
                   |   | \\\  -  /// |   |
                   | \_|  ''\---/''  |   |
                   \  .-\__  `-`  ___/-. /
                 ___`. .'  /--.--\  `. . __
              ."" '<  `.___\_<|>_/___.'  >'"".
             | | :  `- \`.;`\ _ /`;.`/ - ` : | |
             \  \ `-.   \_ __\ /__ _/   .-` /  /
        ======`-.____`-.___\_____/___.-`____.-'======
                           `=---='
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                 佛祖保佑               永无BUG
*/
public class FreeMarkerTemplateUtils {
    //private static String codePath = SystemUtil.getPro("ROOTPATH")+"\\hj_base\\src\\main\\resources\\model";
    //private static String codePath = SystemUtil.getPro("ROOTPATH")+"/hj_base/src/main/resources/model";
    private static String codePath = SystemUtil.getPro("ROOTPATH")+
            File.separator +"hj_base" + File.separator + "src" + File.separator +"main" + File.separator + "resources" +
            File.separator + "model";

    private FreeMarkerTemplateUtils () {
    }

    private static final Configuration CONFIGURATION = new Configuration();

    static {
        //这里比较重要，用来指定加载模板所在的路径
//        CONFIGURATION.setTemplateLoader(new ClassTemplateLoader(FreeMarkerTemplateUtils.class, "/templates"));
        try {
            CONFIGURATION.setDirectoryForTemplateLoading(new File(codePath));
            CONFIGURATION.setDefaultEncoding("UTF-8");
            CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        CONFIGURATION.setCacheStorage();
    }

    public static Template getTemplate (String templateName) throws IOException {
        try {
            return CONFIGURATION.getTemplate(templateName);
        } catch (IOException e) {
            throw e;
        }
    }

    public static void clearCache () {
        CONFIGURATION.clearTemplateCache();
    }
}
